﻿using MaiPlanServer.Dto;
using MaiPlanServer.IRepository;
using MaiPlanServer.IServices.IMasterDataServices;
using MaiPlanServer.Model;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace MaiPlanServer.Services.MasterDataServices
{
    public class MaterialsProductCServices : IMaterialsProductCServices
    {
        public MaterialsProductCServices(IBaseRepository BaseConnn)
        {
            this.BaseConn = BaseConnn;
        }

        public IBaseRepository BaseConn { get; }
        

        public async Task<IEnumerable<MD_ITEM_TYPEDto>> GetJsonAsync(int PageIndex, int PageSize, string typeName, string State)
        {
            string sql = @"select * from MD_ITEM_TYPE where 1=1 and ITEM_TYPE_NAME like @typeName ";
            if (!string.IsNullOrEmpty(State))
            {
                sql += " and ENABLE_FLAG = @State ";
            }
            sql += " order by Create_Time desc offset @PageSize*(@PageIndex-1) rows fetch next @PageSize row only";

            var list = await BaseConn.QueryAsync<MD_ITEM_TYPEDto>(sql, new { PageIndex, PageSize, typeName = "%" + typeName + "%", State });

            return list;
        }

        public async Task<IEnumerable<MD_ITEM_TYPEDto>> GetMdTypeAllAsync()
        {
            string sql = @"select * from MD_ITEM_TYPE";

            var list = await BaseConn.QueryAllAsync<MD_ITEM_TYPEDto>(sql);

            return list;
        }


        public async Task<bool> AddAsync(MD_ITEM_TYPE model)
        {
            var result = await BaseConn.InsertAsync(model);

            return result;
        }


        public async Task<bool> UpdateAsync(MD_ITEM_TYPE model)
        {
            var result = await BaseConn.UpdateAsync(model, "ITEM_TYPE_ID");

            return result;
        }


        public async Task<bool> DelAsync(string Id)
        {
            var sql = @"with tab as(
	                        select * from  MD_ITEM_TYPE where  ITEM_TYPE_ID=@Id
	                        union all 
	                        select child.* from  MD_ITEM_TYPE  child join tab parent on parent.ITEM_TYPE_ID = child.PARENT_TYPE_ID
                             )
                        delete MD_ITEM_TYPE where ITEM_TYPE_ID in (select ITEM_TYPE_ID from tab)";
            var resulr = await BaseConn.DeleteAsync(sql, new { Id = Id });
            return resulr;
        }

    }
}
